package com.echoesnet.echoesshortvideo.Repositories;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;

import com.echoesnet.echoesshortvideo.Api.ApiException;
import com.echoesnet.echoesshortvideo.Api.HttpMethods;
import com.echoesnet.echoesshortvideo.Api.RequestHeader;
import com.echoesnet.echoesshortvideo.Api.Subscriber.SilenceSubscriber;
import com.echoesnet.echoesshortvideo.Constant.Api;
import com.echoesnet.echoesshortvideo.Beans.PublishVideoBean;
import com.echoesnet.echoesshortvideo.Beans.PublishVideoProgressBean;
import com.echoesnet.echoesshortvideo.Utils.CdnUtils.CdnHelper;
import com.echoesnet.echoesshortvideo.Utils.CdnUtils.IOnCdnFeedbackListener;
import com.echoesnet.echoesshortvideo.Utils.SharePreUtils;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import java.io.File;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

/**
 * Copyright (C) 2017 在线回声（天津）科技发展有限公司
 * 在线回声完全享有此软件的著作权，违者必究
 *
 * @author an
 * @version 1.0
 * @modifier
 * @createDate 2018/4/24 0024
 * @description
 */
public class MainRepository
{
    private final static String TAG = MainRepository.class.getSimpleName();
    private MutableLiveData<PublishVideoProgressBean> data;
    private long progress = 0;

    public LiveData<PublishVideoProgressBean> publishVideo(PublishVideoBean publishVideoBean){

        TreeMap<Integer, String> videoMap = new TreeMap<>();
        if (data == null)
            data = new MutableLiveData<>();
        PublishVideoProgressBean publishVideoProgressBean = new PublishVideoProgressBean();
        CdnHelper.getInstance().setOnCdnFeedbackListener(new IOnCdnFeedbackListener()
        {
            @Override
            public void onSuccess(JSONObject response, File file, String fileKeyName, int uploadOrder)
            {
                videoMap.put(uploadOrder, CdnHelper.CDN_ORIGINAL_SITE + fileKeyName);
                if (videoMap.size() == 2)
                {
                    String videoUrl = videoMap.get(0);
                    String thumbnailUrl = videoMap.get(1);
                    Logger.t(TAG).d("视频上传成功 videoUrl =" + videoUrl + "|thumbnailUrl=" + thumbnailUrl);
                    publishVideoBean.setUrl(videoUrl);
                    publishVideoBean.setThumbnails(thumbnailUrl);
                    String content = new Gson().toJson(publishVideoBean);
                    Logger.t(TAG).d("content>>>" + content);
                    Map<String, Object> reqMap = RequestHeader.getCommonPartOfParam();
                    reqMap.put(RequestHeader.VIDEO_CONTENT, content);
                    HttpMethods.getInstance().startServerRequest(new SilenceSubscriber<String>(){
                        @Override
                        public void onNext(String response)
                        {
                            super.onNext(response);
                            Logger.t(TAG).d("response>>>>>>>>>>>>>>" + response);
                            PublishVideoProgressBean publishVideoProgressBean1 = data.getValue();
                            publishVideoProgressBean1.setStatus("0");
                            data.setValue(publishVideoProgressBean1);
                        }

                        @Override
                        public void onHandledError(ApiException apiE)
                        {
                            super.onHandledError(apiE);
                            PublishVideoProgressBean publishVideoProgressBean1 = data.getValue();
                            publishVideoProgressBean1.setStatus("1");
                            publishVideoProgressBean1.setCode(apiE.getErrorCode());
                            data.setValue(publishVideoProgressBean1);
                        }

                        @Override
                        public void onHandledNetError(Throwable throwable)
                        {
                            super.onHandledNetError(throwable);
                            PublishVideoProgressBean publishVideoProgressBean1 = data.getValue();
                            publishVideoProgressBean1.setStatus("1");
                            publishVideoProgressBean1.setCode("NetError");
                            data.setValue(publishVideoProgressBean1);
                        }
                    }, Api.VIDEOC_PUBLISH_VIDEO,reqMap,true);
                }
            }

            @Override
            public void onProcess(long len)
            {
                if (progress != len)
                {
                    progress = len;
                    PublishVideoProgressBean publishVideoProgressBean1 = data.getValue();
                    if (publishVideoProgressBean1 == null)
                        publishVideoProgressBean1 = publishVideoProgressBean;
                    if (len % 10 == 0 || len == 100)
                        publishVideoProgressBean1.setProgress(len);
                    data.setValue(publishVideoProgressBean1);
                }
            }

            @Override
            public void onFail(JSONObject response, File file)
            {
                Logger.t(TAG).d("视频上传失败>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + response.toString());
                publishVideoProgressBean.setStatus("1");
                publishVideoProgressBean.setCode(response.toString());
                data.setValue(publishVideoProgressBean);
            }
        });
        File file = new File(publishVideoBean.getUrl());
        String videoName = CdnHelper.trendsImage + SharePreUtils.getUId() + UUID.randomUUID().toString().substring(0, 8) + ".mp4";
        progress = 0;
        publishVideoProgressBean.setProgress(0);
        data.setValue(publishVideoProgressBean);
        CdnHelper.getInstance().putFile(file, "img", videoName, 0);
        File thumbnailFile = new File(publishVideoBean.getThumbnails());
        if (thumbnailFile.exists())
        {
            Logger.t(TAG).d("缩略图存在");
            String thumbnailName = CdnHelper.trendsImage + SharePreUtils.getUId() + UUID.randomUUID().toString().substring(0, 8) + ".jpg";
            CdnHelper.getInstance().putFile(thumbnailFile, "img", thumbnailName, 1);
        }
        else
        {
            Logger.t(TAG).d("缩略图不存在");
            videoMap.put(1, "");
        }


        return data;
    }
}
